import axios  from "axios";
import { Toast } from 'vant';

const service =axios.create({
    baseURL:process.env.VUE_APP_BASE_URL,
    timeout:5000,
    withCredentials:true,
})

// 请求拦截
service.interceptors.request.use(config => {//token验证
    let token = localStorage.getItem('token') || ''
    config.headers.Authorization = token
    // return config
    Toast.loading({
        message:'加载中啊',
        forbidClick:true
    })
}, err => {
    throw new Error(err)
})


// 响应拦截
service.interceptors.response.use(res => {
    Toast.clear();
    let { status, msg } = res.data.meta
    switch (status) {//根据返回的状态码判断
        case 200:
            ElMessage({
                message: msg,
                type: 'success',
            })
            break;
        case 201:
            ElMessage({
                message: '创建成功',
                type: 'success',
            })
            break;
        case 204:
            ElMessage({
                message: '删除成功',
                type: 'success',
            })
            break;
        case 400:
            ElMessage({
                message: '请求的地址不存在或者包含不支持的参数',
                type: 'success',
            })
            break;
        case 401:
            ElMessage({
                message: '未授权',
                type: 'success',
            })
            break;
        case 403:
            ElMessage({
                message: '被禁止访问',
                type: 'success',
            })
            break;
        case 404:
            ElMessage({
                message: '请求的资源不存在',
                type: 'success',
            })
            break;
        case 422:
            ElMessage({
                message: '发生一个验证错误',
                type: 'success',
            })
            break;
        case 500:
            ElMessage({
                message: '内部错误',
                type: 'success',
            })
            break;
    }
    // 将最终的数据返回出去
    return res.data.data
}, err => {
    // 将错误抛出
    throw new Error(err)
})
//导出

export default service;